package cn.hahah.module.blog.app.controller;

import cn.hahah.framework.common.pojo.CommonResult;
import cn.hahah.module.blog.app.JwtUtils;
import cn.hahah.module.blog.app.dto.ArticleComment;
import cn.hahah.module.blog.app.service.BlogVisitService;
import cn.hahah.module.blog.controller.admin.article.vo.ArticleRespVO;
import cn.hahah.module.blog.controller.admin.users.vo.UsersRespVO;
import cn.hahah.module.blog.dal.dataobject.article.ArticleDO;
import cn.hahah.module.blog.dal.dataobject.articletype.ArticleTypeDO;
import cn.hahah.module.blog.dal.dataobject.tag.TagDO;
import cn.hahah.module.blog.dal.dataobject.users.UsersDO;
import cn.hahah.module.infra.controller.admin.file.vo.file.FileUploadReqVO;
import cn.hahah.module.infra.service.file.FileService;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.Map;

import static cn.hahah.framework.common.pojo.CommonResult.success;
import static cn.hahah.module.infra.framework.file.core.utils.FileTypeUtils.writeAttachment;

@RestController
@Tag(name = "博客访问模块_游客接口")
@RequestMapping("/public/visit")
public class BlogVisitController {

    @Resource
    private BlogVisitService blogVisitService;
    @Resource
    private FileService fileService;
    @Resource
    private JwtUtils jwtUtils;

    /**游客_文件上传*/
    @PostMapping("/upload")
    @Operation(summary = "游客_文件上传")
    public CommonResult<String> uploadFile(FileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        String uuid = jwtUtils.generateUuid();
        String type = file.getContentType().split("/")[1];
        String url = fileService.createFile(
                file.getOriginalFilename(),
                uuid+"."+type,
                IoUtil.readBytes(file.getInputStream()));
        String newUrl = url.replace("/admin-api/infra/file", "/public/visit");
        return success(newUrl);

    }


    /**游客_查看图片*/
    @GetMapping("/{configId}/get/**")
    @PermitAll
    @Operation(summary = "下载文件")
    @Parameter(name = "configId", description = "配置编号", required = true)
    public void getFileContent(HttpServletRequest request,
                               HttpServletResponse response,
                               @PathVariable("configId") Long configId) throws Exception {
        String path = StrUtil.subAfter(request.getRequestURI(), "/get/", false);
        if (StrUtil.isEmpty(path)) {
            throw new IllegalArgumentException("结尾的 path 路径必须传递");
        }
        // 解码，解决中文路径的问题 https://gitee.com/zhijiantianya/ruoyi-vue-pro/pulls/807/
        path = URLUtil.decode(path);

        // 读取内容
        byte[] content = fileService.getFileContent(configId, path);
        if (content == null) {
            System.out.println("[getFileContent][configId({}) path({}) 文件不存在]"+configId+path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        writeAttachment(response, path, content);
    }


    /**游客_首页推荐*/
    @GetMapping("/home/recommend")
    @Operation(summary = "游客_首页推荐")
    public CommonResult<Map<String,Object>> homePageRecommend() {
        return blogVisitService.homePageRecommend();
    }


    /**游客_查看文章详情*/
    @GetMapping("/articleDetail")
    @Operation(summary = "游客_查看文章详情")
    public CommonResult<ArticleDO> articleDetail(
            @RequestParam Long articleId,
            HttpServletRequest request,
            @RequestHeader(value = "Authorization", defaultValue = "1234.1234.1234") String token) {

        Long userId;
        String ipAddress = request.getRemoteAddr();
        System.out.println("hahahahahahahaha"+token);
        try{
            if(!jwtUtils.validateToken(token)){
                userId = null;
            }else {
                userId = jwtUtils.getIdFromToken(token);
            }
        }catch (Exception e){
            System.out.println("hahahahahaah"+e.getMessage());
            userId = null;
        }

        return blogVisitService.articleDetail(userId, ipAddress, articleId);
    }

    /**游客_获取所有文章类型*/
    @GetMapping("/getAllType")
    @Operation(summary = "游客_获取所有文章类型")
    public CommonResult<List<ArticleTypeDO>> getAllType() {
        return blogVisitService.getAllType();
    }


    /**游客_获取所有文章标签*/
    @GetMapping("/getAllTag")
    @Operation(summary = "游客_获取所有文章类型")
    public CommonResult<List<TagDO>> getAllTag() {
        return blogVisitService.getAllTag();
    }


    /**游客_根据文章获取标签*/
    @GetMapping("/getTagByArt")
    @Operation(summary = "游客_根据文章获取标签")
    public CommonResult<List<Long>> getTagByArt(
            @RequestParam Long articleId) {
        return blogVisitService.getTagByArt(articleId);
    }


    /**游客_搜索文章*/
    @GetMapping("/searchArticle")
    @Operation(summary = "游客_搜索文章")
    public CommonResult<List<ArticleRespVO>> searchArticle(
            @RequestParam String title,
            @RequestHeader(value = "Authorization", defaultValue = "1234.1234.1234") String token) {

        Long userId;
        try{
            if(!jwtUtils.validateToken(token)){
                userId = null;
            }else {
                userId = jwtUtils.getIdFromToken(token);
            }
        }catch (Exception e){
            userId = null;
        }

        return blogVisitService.searchArticle(userId, title);
    }

    /**游客_搜索用户*/
    @GetMapping("/searchUser")
    @Operation(summary = "游客_搜索用户")
    public CommonResult<List<UsersRespVO>> searchUser(
            @RequestParam String nickname) {
        return blogVisitService.searchUser(nickname);
    }


    /**游客_根据分类搜索文章*/
    @GetMapping("/searchArtByType")
    @Operation(summary = "游客_根据分类搜索文章")
    public CommonResult<List<ArticleRespVO>> searchArtByType(
            @RequestParam Long typeId) {
        return blogVisitService.searchArtByType(typeId);
    }


    /**游客_根据标签搜索文章*/
    @GetMapping("/searchArtByTag")
    @Operation(summary = "游客_根据标签搜索文章")
    public CommonResult<List<ArticleRespVO>> searchArtByTag(
            @RequestParam Long tagId) {
        return blogVisitService.searchArtByTag(tagId);
    }


    /**游客_获取文章评论*/
    @GetMapping("/getArticleComment")
    @Operation(summary = "游客_获取文章评论")
    public CommonResult<List<ArticleComment>> getArticleComment(
            @RequestParam Long articleId) {
        return blogVisitService.getArticleComment(articleId);
    }


    /**游客_查看用户资料*/
    @GetMapping("/user/profile/{userId}")
    @Operation(summary = "游客_查看用户资料")
    public CommonResult<UsersDO> checkUser(
            @PathVariable Long userId) {
        return blogVisitService.checkUser(userId);
    }

}